package com.huawei.app.demo.task;

import java.security.SecureRandom;

import com.huawei.app.httpapi.ThreadPools;

/**
 * 压力测试任务
 *
 * @since 2021-02-01
 */
public class StressTestTask implements Runnable {

    private String name;
    private boolean running = true;

    public StressTestTask(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        String oldName = Thread.currentThread().getName();
        Thread.currentThread().setName(name);

        while (running) {
            try {
                SecureRandom random = new SecureRandom();
                int n = random.nextInt(100000000);
                long result = calcFibonacci(n);
            } catch (Exception e) {
                // ignore.
            }
        }

        Thread.currentThread().setName(oldName);
    }

    /**
     * 计算斐波那契序列
     * @param n
     * @return
     */
    private long calcFibonacci(long n) {
        if (n <= 0) {
            return 0;
        }
        if (n == 1 || n == 2) {
            return 1;
        }

        long n1 = 1;
        long n2 = 1;
        long result = n1 + n2;
        for (int i=3; i<=n; i++) {
            result = n1 + n2;
            n1 = n2;
            n2 = result;
        }
        return result;
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
}
